/*-=-=-=-=-=-=-=全局变量模块-=-=-=-=-=-=-*/
var imageUrls = [], // 从服务器返回的上传成功图片数组
imageCount = 0; // 预览框中的图片数量，初始为0
var allImage = 0;

/*-=-=-=-=-=-=-=界面生成模块-=-=-=-=-=-=-*/

function switchTab(obj, index) {
	clearFocusClass();
	obj.className = "act";
	g("tabs").style.left = index * (-620) + "px";
	if (obj.getAttribute("name") == "tab2") {
		g("control").style.display = "";
		if (imageCount != 0) {
			dialog.buttons[0].setDisabled(true); // 如果预览框中没有图片或者没有成功上传图片，切回来时重新置灰按钮
		}
	} else {
		g("control").style.display = "none";
		dialog.buttons[0].setDisabled(false); // 切回来时重新点亮按钮
	}
}
function clearFocusClass() {
	var heads = g("head").children;
	for (var i = 0, j; j = heads[i++];) {
		j.className = "def";
	}
}

/*-=-=-=-=-=-=-=逻辑处理模块-=-=-=-=-=-=-*/
// -----------------核心流程------------------------------
var img = editor.selection.getRange().getClosedNode(), oWidth, oHeight, percent;
if (!img)
	img = document.createElement("img");
if (img.src) {
	// 图片编辑时显示图片信息
	showImageInfo();
}
if (document.attachEvent) {
	g("url").onpropertychange = function() {
		if (g("url").value)
			preloadImg();// trace：解决IE下初始提示bug
	};
} else {
	g("url").addEventListener("input", function() {
				preloadImg();
			}, false);
}
// 点击确定时的事件处理
dialog.onok = function() {
	var actionTab = findActionTab();
	if (actionTab == "tab1") {
		return insertSingle();
	} else if (actionTab == "tab2") {
		return insertBatch();
	}
};
// ----------------------------------------------------

/**
 * 返回false时不会关闭对话框
 */
function insertSingle() {
	// 未成功加载图片直接返回
	if (!img.src)
		return;
	// if(img.hasAttribute("word_img") && img.src.indexOf("file:///") == -1){
	// img.removeAttribute("word_img");
	// }
	var imgObj = {
		src : img.src
	};
	var width = g("imgWidth").value;
	if (!width)
		width = oWidth;
	if (!isNum(width)) {
		alert("请输入正确的宽度值！例如：140，200.5");
		g("imgWidth").value = "";
		g("imgWidth").focus();
		return false;
	}
	var height = g("imgHeight").value;
	if (!height)
		height = oHeight;
	if (!isNum(height)) {
		alert("请输入正确的高度值！例如：140，200.5");
		g("imgHeight").value = "";
		g("imgHeight").focus();
		return false;
	}
	var border = g("imgBorder").value;
	if (!border && border != 0 && !isNum(border)) {
		alert("请输入正确的边框值！例如：1，2");
		g("imgBorder").value = "";
		g("imgBorder").focus();
		return false;
	}
	imgObj.width = width;
	imgObj.height = height;
	imgObj.border = border;
	imgObj.title = g("imgTitle").value || "";
	imgObj.floatStyle = getAlign("singleFloat");
	editor.execCommand("insertImage", imgObj);
	img = null;
}

/**
 * 返回false时不会关闭对话框
 */
function insertBatch() {
	if (!imageUrls.length)
		return;
	var imgObjs = [], align = getAlign("batchFloat");

	for (var i = 0, ci; ci = imageUrls[i++];) {
		var tmpObj = {};
		tmpObj.title = ci.title;
		tmpObj.floatStyle = align;
		// 修正显示时候的地址数据,如果后台返回的是图片的绝对地址，那么此处无需修正
		tmpObj.src = editor.options.imagePath + ci.url;
		imgObjs.push(tmpObj);
	}
	editor.execCommand("insertImage", imgObjs);
}

function findActionTab() {
	var heads = g("head").children;
	for (var i = 0, j; j = heads[i++];) {
		var className = j.className;
		if (className == "act") {
			return j.getAttribute("name");
		}
	}
	return "";
}

// 预加载图片
function preloadImg() {

	var imgType = new RegExp("/\.(png|gif|jpg|jpeg)$/ig"), urlFilter = "";
	var url = g("url").value, preview = g("preview");
	if (!imgType.test(url) && url.indexOf(urlFilter) == -1) {
		preview.innerHTML = "不正确的图片格式或者图片域！";
		return;
	}
	preview.innerHTML = "图片加载中……";
	// 修正当修改地址时候img对象已经销毁的问题
	if (!img) {
		img = document.createElement("img");
		img.src = url;
	}
	img.onload = function() {
		oWidth = this.width;
		oHeight = this.height;
		percent = (oWidth / oHeight).toFixed(2);
		setPreview(this, 330);

	};
	img.onerror = function() {
		preview.innerHTML = "图片加载失败，请检查网络！";
		img = null;
	};
	img.src = url;
}

// 显示图片信息
function showImageInfo() {
	// 获取图片float方式
	var align = editor.queryCommandValue('imagefloat');
	replaceImg(align);
	if (img.getAttribute("word_img")) {
		g("url").value = img.getAttribute("word_img").replace("&amp;", "&");
		g("msg").style.display = "";
	} else {
		// g("url").value = img.src.replace("&amp;", "&");
		g("url").value = img.src.replace("&amp;", "&");
	}
	g("imgWidth").value = img.width;
	g("imgHeight").value = img.height;
	g("imgBorder").value = img.getAttribute("border") || 0;
	g("imgTitle").value = img.title;
	setPreview(img, 330);
	percent = (img.width / img.height).toFixed(2);
}

function setPreview(img, max) {
	var tmp = img.cloneNode(true);
	tmp.width = img.width;
	tmp.height = img.height;
	scale(tmp, max);
	g("preview").innerHTML = '<img src="' + tmp.src + '" width="' + tmp.width
			+ '" height="' + tmp.height + '" border="' + img.style.border
			+ '" />';
}
// 更改float的提示图标
function replaceImg(str) {
	var imgs = g("singleFloat").children;
	for (var i = 0; j = imgs[i++];) {
		imgs[0].src = imgs[0].src.replace("-c.jpg", ".jpg");
	}
	for (var i = 0, j; j = imgs[i++];) {
		if (j.getAttribute("name") == str) {
			j.src = j.src.replace(".jpg", "-c.jpg");
			break;
		}
	}
}

/*-=-=-=-=-=-=-=批量上传控制模块-=-=-=-=-=-=-*/
function upload() {
	flashObj.call("upload");
	g("start").style.display = "none";
}
/**
 * 选择文件后的回调函数
 * 
 * @param selectFiles
 */
function selectFileCallback(selectFiles) {
	// if(console)console.log("开始选择文件：");
	imageCount += selectFiles.length;
	allImage += selectFiles.length;
	g("start").style.display = "";
	g("start").onclick = upload;
	dialog.buttons[0].setDisabled(true); // 初始化时置灰确定按钮

}
/**
 * 单个文件上传完成的回调函数
 * 
 * @param Object/String
 *            服务端返回啥，参数就是啥
 */
function uploadCompleteCallback(data) {
	// debugger
	// if(console)console.log("上传成功", data);
	var info = eval("(" + data.info + ")");
	info && imageUrls.push(info);
	imageCount--;
}

// 全部上传完成的回调函数
function allCompleteCallback() {
	// console.log("全部上传成功");
	dialog.buttons[0].setDisabled(false); // 上传完毕后点亮按钮
}

// 全部上传完成的回调函数
function allPhotoCompleteCallback(data) {
	// console.log("全部上传成功");

	var desc = "图片全部上传成功!";

	if (imageCount == allImage) {
		desc = "图片上传失败!";
	} else if (imageCount > 0) {
		desc = "图片部分上传成功!";
	}

	blockDialog.uploadInfoDialog("上传成功", desc, false, function() {

				var showRange = 1;
				var typeId = $("#typeId").val();
				var typeName = $("#typeNameHidden").val();

				$("input[name='RadioGroup1']").each(function() {
							var checked = $(this).attr("checked");
							if (checked) {
								showRange = $(this).val();
							}
						});

				// 关闭提示框
				blockDialog.closeblock();
				var showType = $("#showType").val();
				var url = ctx + "/sns/web/personShow/grxXiangpianLB.do?typeId="
						+ typeId + "&showRange=" + showRange + "&typeName="
						+ encodeURI(encodeURI(typeName)) + "&showType="
						+ showType;
				pageFun.refererLink(url, null, null);
			}, function() {

				// 关闭提示框
				blockDialog.closeblock();
				location.reload();
			});

	dialog.buttons[0].setDisabled(false); // 上传完毕后点亮按钮
}

/**
 * 删除文件后的回调函数
 * 
 * @param Array
 */
function deleteFileCallback(delFiles) {
	// 数组里单个元素为Object，{index:在多图上传的索引号, name:文件名, size:文件大小}
	// 其中size单位为Byte
	imageCount -= delFiles.length;
	allImage -= delFiles.length;
	if (imageCount == 0) {
		g("start").style.display = "none";
		dialog.buttons[0].setDisabled(false); // 上传完毕后点亮按钮
	}
}

/*-=-=-=-=-=-=-=公共方法模块-=-=-=-=-=-=-*/
function g(id) {
	return document.getElementById(id);
}
function isNum(n) {
	return /^[1-9]+[.]?\d*$/g.test(n);
}
/**
 * 获取csstext中的某个样式属性
 * 
 * @param cssText
 * @param style
 */
function getStyleFromCssText(cssText, style) {
	var reg = new RegExp(style + ":\\s*((\\w)*)", "ig");
	var arr = reg.exec(cssText);
	return arr ? arr[1] : "";
}
/**
 * 等比例缩放图片
 * 
 * @param img
 * @param max
 */
function scale(img, max) {
	var width = 0, height = 0, percent;
	img.sWidth = img.width;
	img.sHeight = img.height;
	if (img.width > max || img.height > max) {
		if (img.width >= img.height) {
			if (width = img.width - max) {
				percent = (width / img.width).toFixed(2);
				img.height = img.height - img.height * percent;
				img.width = max;
			}
		} else {
			if (height = img.height - max) {
				percent = (height / img.height).toFixed(2);
				img.width = img.width - img.width * percent;
				img.height = max;
			}
		}
	}
}
function imgselect(simg) {
	var childs = simg.parentNode.children;
	for (var i = 0, child; child = childs[i++];) {
		if (/img/ig.test(child.tagName)) {
			child.src = child.src.replace("-c.jpg", ".jpg");
		}
	}
	simg.src = simg.src.replace(".jpg", "-c.jpg");
}
// 获取id下选中图片的name
function getAlign(id) {
	var imgs = g(id).children;
	for (var i = 0, img; img = imgs[i++];) {
		if (img.src.indexOf("-") != -1) {
			break;
		}
	}
	return i != imgs.length + 1 ? img.name : 'none';
}

var imgWidth = g("imgWidth"), imgHeight = g("imgHeight"), zoom = g('zoom');
imgWidth.onkeyup = function() {
	if (!isNaN(this.value) && zoom.checked) {
		imgHeight.value = Math.round(this.value / percent);
	}
};
imgHeight.onkeyup = function() {
	if (!isNaN(this.value) && zoom.checked) {
		imgWidth.value = Math.round(this.value * percent);
	}
};